import 'package:lib_database/src/model/basemodel.dart';
import 'package:objectbox/objectbox.dart';
import '../../../objectbox.dart';
import '../../../objectbox.g.dart';
import '../../bean.dart';

@Entity()
class CacheDApp {
  @Id()
  int id;
  String? uid;
  String? name;
  String? logo;
  String? url;
  String? description;
  String? statement;
  String? chains;

  CacheDApp(
      {this.id = 0,
      this.uid,
      this.name,
      this.logo,
      this.url,
      this.description,
      this.statement,
      this.chains});

  CacheDApp.fromDApp({this.id = 0, required DAppBean dApp}) {
    name = dApp.name;
    logo = dApp.logo;
    url = dApp.url;
    uid = dApp.uid!;
    description = dApp.description;
    statement = dApp.statement;
    chains = dApp.chains!.join(',');
  }

  static DAppBean toDApp(CacheDApp dApp) {
    DAppBean dAppBean = DAppBean(
        dApp.uid,
        dApp.name,
        dApp.logo,
        dApp.url,
        dApp.description,
        // dApp.chains!.split(',').map((e) => int.parse(e)).toList(growable: false),
        [],
        dApp.statement ?? '');
    return dAppBean;
  }
}

class CacheDAppModel extends BaseModel<CacheDApp> {
  CacheDAppModel(Box<CacheDApp> box) : super(box);

  List<DAppBean> getAllCacheDApp(String uid) {
    return box
        .query(CacheDApp_.uid.equals(uid) as Condition<CacheDApp>?)
        .build()
        .find()
        .map((e) => CacheDApp.toDApp(e))
        .toList(growable: false);
  }

  int getAllCacheLength(String uid) {
    return box
        .query((CacheDApp_.uid.equals(uid)) as Condition<CacheDApp>?)
        .build()
        .count();
  }

  bool isCache(DAppBean dApp) {
    String url = dApp.url!;
    String uid = dApp.uid!;
    // String domain = Uri.parse(url).host;
    // return box
    //         .query(CacheDApp_.url
    //             .startsWith('http://$domain')
    //             .or(CacheDApp_.url.startsWith('https://$domain')))
    //         .build()
    //         .count() >
    //     0;
    return box
            .query((CacheDApp_.uid.equals(uid) &
                    CacheDApp_.url.equals(url, caseSensitive: false))
                as Condition<CacheDApp>?)
            .build()
            .count() >
        0;
  }

  CacheDApp? getCacheOneByUrl({String url = '', required String uid}) {
    return box
        .query((CacheDApp_.uid.equals(uid) &
                CacheDApp_.url.equals(url, caseSensitive: false))
            as Condition<CacheDApp>?)
        .build()
        .findFirst();
  }

  bool addCacheDApp(DAppBean dApp) {
    if (isCache(dApp)) {
      return false;
    }
    return box.put(CacheDApp.fromDApp(dApp: dApp)) > 0;
  }

  bool removeCacheDApp(DAppBean dApp) {
    String url = dApp.url!;
    List<int> ids = box
        .query(CacheDApp_.url.equals(url) as Condition<CacheDApp>?)
        .build()
        .findIds();
    if (ids.isNotEmpty) {
      return box.removeMany(ids) > 0;
    } else {
      return false;
    }
  }
}
